package com.oa.crm.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.mdp.core.err.BizException;
import com.mdp.core.service.BaseService;
import com.oa.crm.common.CrmUtils;
import com.oa.crm.entity.CustomerContacter;
import com.oa.crm.enums.CustomerContacterEnum;
import com.oa.crm.enums.CustomerOpertionEnum;
import com.oa.crm.mapper.CustomerContacterMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author maimeng-mdp code-gen
 * @since 2023年10月8日
 */
@Service
public class CustomerContacterService extends BaseService<CustomerContacterMapper, CustomerContacter> {
    static Logger logger = LoggerFactory.getLogger(CustomerContacterService.class);

    /**
     * 自定义查询，支持多表关联
     *
     * @param page 分页条件
     * @param ew   一定要，并且必须加@Param("ew")注解
     * @param ext  如果xml中需要根据某些值进行特殊处理，可以通过这个进行传递，非必须，注解也可以不加
     * @return
     */
    public List<Map<String, Object>> selectListMapByWhere(IPage page, QueryWrapper ew, Map<String, Object> ext) {
        return baseMapper.selectListMapByWhere(page, ew, ext);
    }

    @Autowired
    private CustomerOpertionService customerOpertionService;

    /**
     * 修改客户联系人
     *
     * @param after
     */
    @Transactional
    public void updateCustomerContacter(CustomerContacter after, String ipAddress) throws IllegalAccessException, JsonProcessingException {
        //1.查询该条数据
        CustomerContacter before = this.selectOneObject(after);
        String customerId = after.getCustomerId();

        Map<String, Object> queryarams = new HashMap<>();
        queryarams.put("customerId", customerId);
        //2.如果该条记录被设置为主联系人则先修改其他所有联系人为非主联系人
        if (CustomerContacterEnum.MAIN_CONTACTER.getCode().equals(after.getIsMain())) {
            queryarams.put("isMain", CustomerContacterEnum.NOT_MAIN_CONTACTER.getCode());
            baseMapper.updateContacterMain(queryarams);
        } else {
            //如果该客户联系人只有一个，那么不允许他设置为非主联系人
//			long count = this.countByWhere(queryarams);
            // TODO ？？？？？？？
            long count = super.countByWhere((CustomerContacter) queryarams);
            if (count <= 1) {
                after.setIsMain(CustomerContacterEnum.MAIN_CONTACTER.getCode());
            }
            ;
        }

        //3.更新数据
//        this.updateByPk(after);
        this.updateById(after);

        //4.添加操作日志
        List<Map<String, Object>> operList = CrmUtils.getNotEqualsParams(before, after);
        customerOpertionService.addOperHistory(customerId, CrmUtils.obj2Json(operList), CustomerOpertionEnum.OPER_UPDATE.getCode(), ipAddress);
    }

    /**
     * 删除客户联系人
     *
     * @param customerContacter
     */
    public void deleteCustomerContacter(CustomerContacter customerContacter, String ipAddress) throws JsonProcessingException {
        String customerId = customerContacter.getCustomerId();
        Map<String, Object> queryarams = new HashMap<>();
        queryarams.put("customerId", customerId);

        //1.查询是否只有一个联系人
        // TODO ????????????
//        long count = this.countByWhere(queryarams);
        long count = super.countByWhere((CustomerContacter) queryarams);


        if (count <= 1) {
            throw new BizException("该客户只存在一个联系人，不能删除");
        }

        //2.如果该条记录时主要联系人需要给另外一条数据设置默认联系人
        //查询数据
        queryarams.put("contacterId", customerContacter.getContacterId());
        CustomerContacter updateData = baseMapper.getCustomerContacterlimit1(queryarams);
        updateData.setIsMain(CustomerContacterEnum.MAIN_CONTACTER.getCode());
//        this.updateByPk(updateData);
        baseMapper.updateById(updateData);
        //3.删除数据
//        this.deleteByPk(customerContacter);
        baseMapper.deleteById(customerContacter);

        //4.添加操作日志
        //添加删除日志
        customerOpertionService.addOperHistory(customerId, CrmUtils.obj2Json(CrmUtils.paramsTransferOper("", "是否主联系人", "0", "1")), CustomerOpertionEnum.OPER_DELETE.getCode(), ipAddress);
    }

    /**
     * 更新客户联系人的上级客户
     *
     * @param customerContacter
     */
    public void editContacterParent(Map<String, Object> customerContacter) {
        baseMapper.updateContacterParent(customerContacter);
    }

    //添加客户联系人
    @Transactional
    public void insertContacter(CustomerContacter customerContacter) {
        if (StringUtils.isEmpty(customerContacter.getCustomerId())) {
            throw new BizException("添加联系人错误, 未关联到具体客户");
        }

        Map<String, Object> queryarams = new HashMap<>();
        queryarams.put("customerId", customerContacter.getCustomerId());

        //2.如果该条记录被设置为主联系人则先修改其他所有联系人为非主联系人
        if (CustomerContacterEnum.MAIN_CONTACTER.getCode().equals(customerContacter.getIsMain())) {
            queryarams.put("isMain", CustomerContacterEnum.NOT_MAIN_CONTACTER.getCode());
            baseMapper.updateContacterMain(queryarams);
        }


        //3.插入数据
        this.insert(customerContacter);
    }

    public List<CustomerContacter> selectContacterByCpIds(List<String> customerIds) {
        return baseMapper.selectContacterByCpIds(customerIds);
    }

    public List<Map<String, Object>> getContacterBirthdayCount(Map<String, Object> customerContacter) {
        return baseMapper.getContacterBirthdayCount(customerContacter);
    }
}

